import MockJs from 'mockjs';
import * as proxy from './proxy';

const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || '/';

/**
 * Mockjs 重写xhr之后，withCredentials覆盖了原来的设置，导致无法携带cookies
 */
MockJs.XHR.prototype.__send = MockJs.XHR.prototype.send;
MockJs.XHR.prototype.send = function() {
  if (this.custom.xhr) {
    this.custom.xhr.withCredentials = this.withCredentials || false;
  }
  this.__send.apply(this, arguments);
};

// 动态加载 mock 文件
const files = require.context('./', true, /\w+\/*.js$/);
const fileNames = files.keys();
let mockList = [];
fileNames.forEach(item => {
  const itemApi = files(item).default;
  if (itemApi && itemApi instanceof Array) {
    mockList = [...mockList, ...itemApi];
  }
});

function makeProxyTempte(set) {
  const { url, template, type = 'get', proxyUrl, log } = set;
  if (proxyUrl) {
    return options => {
      let params = undefined;
      try {
        params = JSON.parse(options && options.body);
      } catch (e) {
        console.log(e);
      }
      const data = proxy[type.toLowerCase()](proxyUrl, params, {
        async: false, // 必须要使用同步请求
        rurl: url,
      });
      log &&
        console.log(
          `%c > Mock Api Proxy`,
          'color:#1890ff',
          '\n',
          `From：${url} `,
          '\n',
          `To：${proxyUrl || ''} `,
          '\n',
          `data：`,
          data,
        );
      return data;
    };
  } else {
    return template || '';
  }
}

mockList.forEach(item => {
  const { url, type = 'get', off, regExp = false } = item;
  // url 默认使用正则匹配，如果要自定义正则，可以设置 regExp 打开
  // 严格匹配 url 路径，支持携带 query 参数
  const finalUrl =
    typeof url === 'string' && url.match(/http:/) ? url : API_BASE_URL.replace(/(\/)$/, '') + url;
  const urlRaw = regExp ? finalUrl : new RegExp(finalUrl + '(\\?\\S+=\\S+)?$');
  if (url && !off) {
    MockJs.mock(urlRaw, type.toLowerCase(), makeProxyTempte(item));
  }
});
